/**
 * 性能测试工具
 * 用于测试UserManagement组件的性能改进效果
 */

import { requestDebugger } from './requestDebugger';

interface PerformanceTestResult {
  testName: string;
  requestCount: number;
  duplicateRequests: number;
  averageResponseTime: number;
  passed: boolean;
  details: string;
}

class PerformanceTest {
  private results: PerformanceTestResult[] = [];

  /**
   * 测试页面加载性能
   */
  async testPageLoad(): Promise<PerformanceTestResult> {
    const testName = '页面加载测试';
    
    // 清除之前的请求记录
    requestDebugger.clear();
    
    // 等待页面加载完成
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    const stats = requestDebugger.getRequestStats();
    const requestCount = stats?.totalRequests || 0;
    const duplicateRequests = this.countDuplicateRequests(stats?.recentRequests || []);
    
    const result: PerformanceTestResult = {
      testName,
      requestCount,
      duplicateRequests,
      averageResponseTime: 0,
      passed: requestCount <= 3 && duplicateRequests === 0, // 期望最多3个请求，无重复
      details: `发送了${requestCount}个请求，${duplicateRequests}个重复请求`
    };
    
    this.results.push(result);
    return result;
  }

  /**
   * 测试搜索防抖效果
   */
  async testSearchDebounce(): Promise<PerformanceTestResult> {
    const testName = '搜索防抖测试';
    
    requestDebugger.clear();
    
    // 模拟快速输入
    const searchInput = document.querySelector('input[placeholder*="搜索"]') as HTMLInputElement;
    if (searchInput) {
      // 快速输入多个字符
      ['a', 'ab', 'abc', 'abcd'].forEach((value, index) => {
        setTimeout(() => {
          searchInput.value = value;
          searchInput.dispatchEvent(new Event('input', { bubbles: true }));
        }, index * 50); // 50ms间隔快速输入
      });
    }
    
    // 等待防抖完成
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const searchRequests = this.countSearchRequests(stats?.recentRequests || []);
    
    const result: PerformanceTestResult = {
      testName,
      requestCount: searchRequests,
      duplicateRequests: 0,
      averageResponseTime: 0,
      passed: searchRequests <= 1, // 期望只有1个搜索请求（防抖后）
      details: `快速输入4次，实际发送${searchRequests}个搜索请求`
    };
    
    this.results.push(result);
    return result;
  }

  /**
   * 测试分页性能
   */
  async testPagination(): Promise<PerformanceTestResult> {
    const testName = '分页测试';
    
    requestDebugger.clear();
    
    // 模拟点击分页
    const paginationButtons = document.querySelectorAll('.ant-pagination-item');
    if (paginationButtons.length > 1) {
      (paginationButtons[1] as HTMLElement).click();
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const userRequests = this.countUserRequests(stats?.recentRequests || []);
    const roleRequests = this.countRoleRequests(stats?.recentRequests || []);
    
    const result: PerformanceTestResult = {
      testName,
      requestCount: userRequests + roleRequests,
      duplicateRequests: 0,
      averageResponseTime: 0,
      passed: userRequests === 1 && roleRequests === 0, // 期望只有1个用户请求，0个角色请求
      details: `分页时发送${userRequests}个用户请求，${roleRequests}个角色请求`
    };
    
    this.results.push(result);
    return result;
  }

  /**
   * 运行所有测试
   */
  async runAllTests(): Promise<PerformanceTestResult[]> {
    // console.log('🧪 开始性能测试...');
    
    try {
      await this.testPageLoad();
      await this.testSearchDebounce();
      await this.testPagination();
    } catch (error) {
      console.error('性能测试失败:', error);
    }
    
    this.printResults();
    return this.results;
  }

  /**
   * 打印测试结果
   */
  private printResults() {
    console.log('\n📊 性能测试结果:');
    console.log('='.repeat(50));
    
    this.results.forEach(result => {
      const status = result.passed ? '✅ 通过' : '❌ 失败';
      console.log(`${status} ${result.testName}`);
      console.log(`   ${result.details}`);
    });
    
    const passedCount = this.results.filter(r => r.passed).length;
    const totalCount = this.results.length;
    
    console.log('='.repeat(50));
    console.log(`总计: ${passedCount}/${totalCount} 个测试通过`);

    if (passedCount === totalCount) {
      console.log('🎉 所有性能测试通过！');
    } else {
      console.log('⚠️ 部分测试失败，需要进一步优化');
    }
  }

  /**
   * 统计重复请求
   */
  private countDuplicateRequests(requests: any[]): number {
    const requestMap = new Map<string, number>();
    
    requests.forEach(req => {
      const key = `${req.method} ${req.url}`;
      requestMap.set(key, (requestMap.get(key) || 0) + 1);
    });
    
    let duplicates = 0;
    requestMap.forEach(count => {
      if (count > 1) {
        duplicates += count - 1;
      }
    });
    
    return duplicates;
  }

  /**
   * 统计搜索请求
   */
  private countSearchRequests(requests: any[]): number {
    return requests.filter(req => 
      req.url.includes('/users') && req.params?.search
    ).length;
  }

  /**
   * 统计用户请求
   */
  private countUserRequests(requests: any[]): number {
    return requests.filter(req => 
      req.url.includes('/users') && req.method === 'GET'
    ).length;
  }

  /**
   * 统计角色请求
   */
  private countRoleRequests(requests: any[]): number {
    return requests.filter(req => 
      req.url.includes('/roles') && req.method === 'GET'
    ).length;
  }

  /**
   * 清除测试结果
   */
  clear() {
    this.results = [];
  }
}

// 创建全局实例
export const performanceTest = new PerformanceTest();

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).performanceTest = performanceTest;
}
